<?php

if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
require_once ('./application/controllers/authenticate.php');

class Category extends Authenticate {
	
	function __construct() {
		parent::__construct ();
		$this->load->model ( 'category_model' );
		$this->load->library ( 'html/control/fx_control' );
		$this->load->library ( 'html/control/fx_filter' );
		$this->load->library ( 'html/control/fx_sort' );
		$this->category_model->addAttributeOrder ( 'id', 'desc' );
	}
	
	protected function _eventLoadLayout() {
		$this->page ['title'] = 'Catalog Category Management';
		$this->module ['title'] = 'Catalog Category Management';
		$this->module ['grid'] ['records'] = 20;
		$this->module ['grid'] ['page_range'] = 5;
	}
	
	function index() {
		$data = $this->_initGridView ();
		$this->setPageContent ( 'catalog/category/grid', $data );
		$this->renderLayout ();
	}
	
	protected function _initGridView() {
		
		// Get Paginator Params
		$page = $this->input->getParam ( 'page' );
		$recordPerPage = $this->input->getParam ( 'recordPerPage' );
		if (! $recordPerPage) {
			$recordPerPage = $this->module ['grid'] ['records'];
		}
		
		// Get Filter Params
		$filters = $this->input->post ( 'categoryFilter' );
		// Filter
		$this->fx_filter->filter ( $filters, $this->category_model );
		
		// Get Order Params
		$order = $this->input->post ( 'categoryOrder' );
		// Sort
		$this->fx_sort->sort ( $order, $this->category_model );
		// Get total found records
		$found = $this->category_model->countTotal ();
		
		// Paginate
		$this->load->library ( "tree/paginator/engine/st_paginator_collection" );
		$this->load->library ( "tree/paginator/st_paginator" );
		$this->st_paginator_collection->setModel ( $this->category_model );
		$this->st_paginator->setConfig ( array ('engine' => $this->st_paginator_collection, 'pageRange' => $this->module ['grid'] ['page_range'], 'itemCountPerPage' => $recordPerPage, 'currentPageNumber' => $page ) );
		
		// Paginate Collection
		$collection = $this->st_paginator->getItemsByPage ( $page );
		if (empty ( $collection )) {
			$collection = array ();
		}
		$data = array ();
		$data ['found'] = $found;
		$data ['sorter'] = $this->fx_sort;
		$data ['filters'] = $this->fx_filter;
		$data ['paginator'] = $this->st_paginator;
		$data ['category_ids'] = $this->input->post ( 'category_ids' );
		$data ['category_ids_array'] = explode ( ',', $this->input->post ( 'category_ids' ) );
		$data ['collection'] = $collection;
		return $data;
	}
	
	function edit() {
		try {
			$id = $this->input->getParam ( 'id' );
			if ($id) {
				$this->category_model->loadByPK ( $id );
			}
			$data ['model'] = $this->category_model;
			$data ['parents'] = $this->category_model->getCollection ();
			$this->setPageContent ( 'catalog/category/edit', $data );
			$this->renderLayout ( 'layouts/ajax' );
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	function save() {
		try {
			$id = $this->input->post ( 'category_id' );
			if ($id) {
				$this->category_model->loadByPK ( $id );
			}
			$parent = $this->input->post ( 'category_parent' );
			if (! $parent) {
				$parent = 0;
			} else {
				if (! $this->category_model->isLoaded ()) {
					$this->category_model->setCreatedAt ( "NOW()" );
				}
			}
			// Upload File
			$config ['upload_path'] = './media/category/banners/';
			$config ['allowed_types'] = 'gif|jpg|png';
			$this->load->library ( 'upload', $config );
			$this->upload->do_upload ( 'category_banner' );
			// Get Params
			$this->category_model->setUpdatedAt ( "NOW()" );
			$dataUpload = $this->upload->data ();
			$name = $this->input->post ( 'category_name' );
			$code = $this->input->post ( 'category_code' );
			$summary = $this->input->post ( 'category_summary' );
			$status = $this->input->post ( 'category_status' );
			$meta_title = $this->input->post ( 'category_meta_title' );
			$meta_keywords = $this->input->post ( 'category_meta_keywords' );
			$meta_description = $this->input->post ( 'category_meta_desc' );
			// General Information
			$this->category_model->setUserId ( 1 );
			$this->category_model->setEntityTypeId ( 1 );
			$this->category_model->setParentId ( $parent );
			$this->category_model->setName ( $name );
			$this->category_model->setCode ( $code );
			$bannerPath = 'media/category/banners/' . $dataUpload ['file_name'];
			if (strlen ( $dataUpload ['file_name'] ) > 0) {
				$this->category_model->setBanner ( $bannerPath );
			}
			$this->category_model->setSummary ( $summary );
			$this->category_model->setIsActive ( $status );
			// Meta Information
			$this->category_model->setMetaTitle ( $meta_title );
			$this->category_model->setMetaKeywords ( $meta_keywords );
			$this->category_model->setMetaDesc ( $meta_description );
			// Save Information
			$this->category_model->save ();
			$this->category_model->resetFilteredList ()->addAttributeToFilter ( 'code', $code, 'LIKE' )->loadByFilter ();
			$newId = $this->category_model->getId ();
			if ($parent == 0) {
				$this->category_model->setLevel ( 1 );
				$this->category_model->setPath ( '/0/' . $newId );
			} else {
				$parentCategory = new category_model ();
				$parentCategory->loadByPK ( $parent );
				if ($parentCategory->isLoaded ()) {
					$parentLevel = $parentCategory->getLevel ();
					$parentPath = $parentCategory->getPath ();
					$this->category_model->setLevel ( ++ $parentLevel );
					$this->category_model->setPath ( $parentPath . '/' . $newId );
				}
			}
			$this->category_model->save ();
			if ($newId) {
				$this->st_registry->register ( 'admin/catalog/category/message', 'Update successful' );
				redirect ( site_url ( "admin/catalog/category/index/id/" . $newId, true ) );
			} else {
				$this->st_registry->register ( 'admin/catalog/category/message', 'Add new category successful' );
				redirect ( site_url ( "admin/catalog/category/index", true ) );
			}
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	function delete() {
		try {
			$id = $this->input->getParam ( 'id' );
			if ($id) {
				$this->category_model->loadByPK ( $id );
				$name = $this->category_model->getName ();
				$this->category_model->delete ();
				$this->st_registry->register ( 'admin/catalog/category/message', "Delete category $name successful" );
				redirect ( site_url ( 'admin/catalog/category/index', true ) );
			}
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/category/error', $ex->getMessage () );
			redirect ( site_url ( 'admin/catalog/category/index', true ) );
		}
	}
	
	function massActive() {
		try {
			// Load Category Model
			$ids = $this->input->getMassValues ( 'category_ids' );
			if ($ids) {
				$this->category_model->query ( "update catalog_category set is_active = 1 where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/catalog/category/message', "Active [$countItem] categories successfully" );
			redirect ( site_url ( "admin/catalog/category/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/category/error', $ex->getMessage () );
			redirect ( site_url ( "admin/catalog/category/index", true ) );
		}
	}
	
	function massDeactive() {
		try {
			// Load Category Model
			$ids = $this->input->getMassValues ( 'category_ids' );
			if ($ids) {
				$this->category_model->query ( "update catalog_category set is_active = 0 where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/catalog/category/message', "Active [$countItem] categories successfully" );
			redirect ( site_url ( "admin/catalog/category/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/category/error', $e->getMessage () );
			redirect ( site_url ( "admin/catalog/category/index", true ) );
		}
	}
}